package org.example;

import com.google.protobuf.InvalidProtocolBufferException;
import org.example.proto.UserProtoBuf;

import java.util.Arrays;

//学习地址 - https://wkijriqbpn.feishu.cn/drive/folder/IzSQfOJG9lgcdMdV1i4cQ0pinTg
public class Main {
    public static void main(String[] args) {
        // 将数据序列化
        byte[] byteData = getClientPush();
        System.out.println("获取到字节数据：byteData长度="+ byteData.length);
        System.out.println("获取到字节数据："+ Arrays.toString(byteData));
        System.out.println("===========");


        /**
         * 接收数据反序列化：将字节数据转化为对象数据
         */
        UserProtoBuf.User user = null;
        try {
            user = UserProtoBuf.User.parseFrom(byteData);
        } catch (InvalidProtocolBufferException e) {
            throw new RuntimeException(e);
        }
        System.out.println("user=" + user.toString());
        System.out.println("UserName=" + user.getUserName());
        System.out.println("Timestamp=" + user.getTimestamp());
        System.out.println("Height=" + user.getHeight());
    }

    /**
     * 模拟发送方，将数据序列化后发送
     * @return
     */
    private static byte[] getClientPush() {
        // 按照定义的数据结构，创建一个对象。
        UserProtoBuf.User.Builder user = UserProtoBuf.User.newBuilder();
        user.setAge(18);
        user.setTimestamp(System.currentTimeMillis());
        user.setEnabled(true);
        user.setHeight(1.88F);
        user.setWeight(66.76D);
        user.setUserName("ZhaoYun");
        user.setFullAddress("CH-SC-CD");

        /**
         * 发送数据序列化：将对象数据转化为字节数据输出
         */
        UserProtoBuf.User userBuild = user.build();
        return userBuild.toByteArray();
    }
}